﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WhsFacebook.Net.Web.Database;

namespace WhsFacebook.Net.Web.Facebook.Handlers
{
    /// <summary>
    /// Summary description for PostAuthorize
    /// 
    /// see http://wiki.developers.facebook.com/index.php/Authorizing_Applications
    /// see http://wiki.developers.facebook.com/index.php/Your_callback_page_and_you
    /// </summary>
    public class PostAuthorize : SafeHttpHandler
    {

        protected override void ProcessRequestSafe(HttpContext context)
        {
            if (string.IsNullOrEmpty(FacebookConverter.ToString(context.Request.Params["fb_sig_time"])))
                throw new InvalidOperationException("This URL is to be called from Facebook only!");

            // gather all data
            var auth = FacebookConverter.ToBoolean(context.Request.Params["fb_sig_added"]);
            var loggedIn = !FacebookConverter.ToBoolean(context.Request.Params["fb_sig_logged_out_facebook"]);
            var ts = FacebookConverter.FromUnixTime(context.Request.Params["fb_sig_time"]);
            var viaUser = FacebookConverter.ToInt64(context.Request.Params["fb_sig_profile_user"]);
            var sid = FacebookConverter.ToString(context.Request.Params["fb_sig_session_key"]);
            var locale = FacebookConverter.ToString(context.Request.Params["fb_sig_locale"]);
            var uid = FacebookConverter.ToInt64(
                context.Request.Params["fb_sig_user"] ??
                context.Request.Params["fb_sig_canvas_user"]
                );

            var friends = (FacebookConverter.ToString(context.Request.Params["fb_sig_friends"]) ?? string.Empty).Split(',').Select(FacebookConverter.ToInt64);

            // log
            using (var e = new WhsFacebookEntities())
            {
                DbUserActionLog ua;

                if (auth)
                {
                    ua = new DbUserAuthorizeLog()
                    {
                        FacebookUserId = uid,
                        IsLoggedIn = loggedIn,
                        Occurrence = ts,
                        SessionId = sid,
                        ViaFacebookUserId = viaUser,
                        UserLocale = locale,
                    };
                }
                else
                {
                    ua = new DbUserVisitLog()
                    {
                        FacebookUserId = uid,
                        IsLoggedIn = loggedIn,
                        Occurrence = ts,
                        SessionId = sid,
                        ViaFacebookUserId = viaUser,
                        UserLocale = locale,
                    };
                }

                foreach (var friend in friends)
                {
                    ua.Friends.Add(new DbUserActionLogFriend()
                    {
                        FacebookUserId = uid,
                        FriendUserId = friend,
                    });
                }

                e.AddToUserActionsLog(ua);
                e.SaveChanges();
            }
        }

    }
}